package com.example.demo.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * Copyright(C), 2020-2021, AmbroseCdMeng
 * FileName:    SysUser
 * Author:      AmbroseCdMeng
 * Date:        2021/3/4 9:50
 * Description: 用户实体
 * History:
 * <author>     <time>      <version>       <desc>
 * 作者姓名     修改时间        版本号           描述
 */
@Entity
@Data
@NoArgsConstructor
public class SysUser implements UserDetails {
    /**
     * 主键。自动增长
      */
    @Id
    @GeneratedValue
    private long id;

    /**
     * 姓名。必需且唯一
     */
    @Column(nullable = false, unique = true)
    private String name;

    /**
     * 密码。
     */
    private String password;

    /**
     * 中文名。
     */
    private String cnname;

    /**
     * 是否启用。默认：是
     */
    private Boolean enabled = Boolean.TRUE;

    /**
     * 构造器
     */
    public SysUser(String name, String password){
        this.name = name;
        this.password = password;
    }

    /**
     * 用户角色。多对多映射
     */
    @ManyToMany(cascade = {CascadeType.REFRESH}, fetch = FetchType.EAGER)
    private List<SysRole> roles;

    /**
     * 根据自定义逻辑来返回用户权限。
     * 如果用户权限返回空，或者和拦截路径对应权限不同，则验证不通过。
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<SysRole> roles = this.getRoles();
        for (SysRole role: roles){
            authorities.add(new SimpleGrantedAuthority(role.getRole()));
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return null;
    }

    @Override
    public String getUsername() {
        return null;
    }

    @Override
    public boolean isAccountNonExpired() {
        return false;
    }

    @Override
    public boolean isAccountNonLocked() {
        return false;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }

    @Override
    public boolean isEnabled() {
        return false;
    }
}
